package cn.kgc.psringboot.config;

import cn.kgc.psringboot.realm.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;


/**
 * @author: mosin
 * @version: v1.0  2022/11/17
 * shiro的配置类
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 自定义资源的认证 和放行
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        //注册页可匿名访问  anon
        map.put("/register.jsp", "anon");
        // 放行登录请求
        map.put("/user/login", "anon");
        // 放行注册请求
        map.put("/user/register", "anon");
        map.put("/500.jsp", "anon");
        //  authc  需要认证的资源
        map.put("/**", "user");
        //设置拦截路径  认证路径
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置登录页
        shiroFilterFactoryBean.setLoginUrl("/log.jsp");
        return  shiroFilterFactoryBean;
    }



    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //创建记住我的管理对象
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        SimpleCookie jzw = new SimpleCookie("jzw");
        jzw.setMaxAge(60);
        cookieRememberMeManager.setCookie(jzw);
        //自定义cookie参数
        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);
        // 设置realm
        defaultWebSecurityManager.setRealm(realm);
        return  defaultWebSecurityManager;
    }


    @Bean
    public Realm realm(){
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);

        EhCacheManager ehCacheManager = new EhCacheManager();
        // 设置域对象的缓存对象
        customerRealm.setCacheManager(ehCacheManager);
        // 开启缓存
        customerRealm.setCachingEnabled(true);

        //开启授权的缓存
        customerRealm.setAuthorizationCachingEnabled(true);

        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return  customerRealm;
    }


}
